package com.yonyou.jrmob.lryapp.fragment;


import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.hss01248.dialog.StyledDialog;
import com.yonyou.jr.mob.rzkh.R;
import com.yonyou.jrmob.lryapp.activity.IntroduceActivity;
import com.yonyou.jrmob.lryapp.login.LoginActivity;
import com.yonyou.uap.emm.util.EnterpriseMobileManager;
import com.yonyou.uap.um.service.ServiceCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.bingoogolapple.titlebar.BGATitleBar;
import de.hdodenhof.circleimageview.CircleImageView;
import jrmob.yonyou.com.commonlib.app_config_tool.constant.Constant;
import jrmob.yonyou.com.commonlib.app_config_tool.gkh.MAServices_gkh;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.ChangeHeadImgObserverTD;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.ChangeHeadImgObserverUtilTD;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.HttpUtil;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.CommonUtil;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.LogUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.UiUtils;
import jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib;
import jrmob.yonyou.com.commonlib.baseui.base.BaseApp_lib;
import jrmob.yonyou.com.commonlib.baseui.fragment.BaseFragmentMob_lib;
import jrmob.yonyou.com.commonlib.login.bean.UserInfoLRY;

import static com.iflytek.speech.Version.getVersionName;
import static jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib.readLocationValue;
import static jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib.writeLocationFile;

//import com.yonyou.jrmob.contacts.contact.activity.ContactsDetailActivity_ct;
//import com.yonyou.jrmob.contacts.contact.bean.ContactsVO_ct;
//import com.yonyou.jrmob.contacts.contact.utils.GlideCircleTransform_ct;

public class MyFragment extends BaseFragmentMob_lib implements ChangeHeadImgObserverTD {
    @BindView(R.id.normal_title_bar_status_bar)
    View normalTitleBarStatusBar;
    @BindView(R.id.normal_title_bar)
    BGATitleBar normalTitleBar;
    @BindView(R.id.my_head_imageView)
    CircleImageView myHeadImageView;
    @BindView(R.id.my_name)
    TextView myName;
    @BindView(R.id.my_account)
    TextView myAccount;
    @BindView(R.id.my_click_to_my_detail)
    TextView myClickToMyDetail;
    @BindView(R.id.my_introduce)
    TextView myIntroduce;
    @BindView(R.id.my_update_red_point)
    ImageView myUpdateRedPoint;
    @BindView(R.id.my_update_text)
    TextView myUpdateText;
    @BindView(R.id.my_click_update)
    LinearLayout myClickUpdate;
    @BindView(R.id.my_feedback)
    TextView myFeedback;
    @BindView(R.id.my_logout)
    TextView myLogout;
    Unbinder unbinder;
    private View rootView;
    private View statusBar;
    private Dialog loadingDialog;
//    public ContactsVO_ct contacts;

    public MyFragment() {
        // Required empty public constructor
    }

    @Override
    public View initViews() {
        rootView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_my, null);
        statusBar = rootView.findViewById(R.id.normal_title_bar_status_bar);
        ChangeHeadImgObserverUtilTD.getInstance().registerChangeHeadImgObserver(this);
        return rootView;
    }
    @Override
    public void update(String url) {
        Glide.with(getActivity())
                .load(url)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop()
                .into(myHeadImageView);
    }
    private void initTitleBar() {
        normalTitleBar.setTitleText("我的");
        //statusBar.setBackgroundColor(getResources().getColor(R.color.white));
        //LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) statusBar.getLayoutParams();
        //lp.height = UiUtils.getStatusBarHeight();
        //statusBar.setLayoutParams(lp);
    }

    @Override
    public void initData() {
        myUpdateText.setText("↑"+readLocationValue("app_version"));
        callService();
    }

    private void callService() {
        JSONObject json = new JSONObject();
        try {
            json.put("transtype", Constant.TRANSTYPE_MY_INFO);
            json.put("user_id", ((BaseActivityMob_lib) getActivity()).getUserInfoLRY().getUser_id());
            json.put("uuidToken", Constant.TOKEN);
            if (!CommonUtil.isNetworkConnected(getActivity())) {
                CommonUtil.showToast(getActivity(), "当前网络不可用,请检查!");
                return;
            }
            MAServices_gkh.callMACommonService(getActivity(), new ServiceCallback() {
                @Override
                public void execute(JSONObject json) {
                    LogUtils.e("我的数据：" + json.toString());
                    JSONObject jsArray;
//                    try {
//                        Object obj = json.opt("code");
//                        // 有错误的时候
//                        if (null != obj && obj.toString().trim().equals("0")) {
//                            String msg = json.optString("message").toString().trim();
//                            ((BaseActivityMob_lib) getActivity()).showMessage(msg);
//                            if (msg.contains("请重新登录")) {
//                            }
//                            return;
//                        }
//                        jsArray = (JSONObject) json.get("userInfo");
//                        contacts = new ContactsVO_ct();
//                        contacts.setContactName(jsArray.optString("user_name"));
//                        contacts.setVdef(jsArray.optString("user_mobile"));
//                        contacts.setConcernstatus(jsArray.optString("concernstatus"));
//                        contacts.setContactTel(jsArray.optString("user_telephone"));
//                        contacts.setUser_email(jsArray.optString("user_mail"));
//                        contacts.setCuserId(jsArray.optString("cuserid"));
//                        contacts.setGroupName(jsArray.optString("user_dept"));
//                        contacts.setOrgName(jsArray.optString("user_org"));
//                        contacts.setPerson_code(jsArray.optString("person_code"));
//                        contacts.setPerson_id(jsArray.optString("person_id"));
//                        contacts.setPerson_logo(jsArray.optString("person_logo"));
//                        if (contacts.getPerson_logo().contains("\\?")) {
////                            contacts.setPerson_logo(contacts.getPerson_logo().split("\\?")[0]);
//                        }
//                        myAccount.setText(contacts.getPerson_code());
//                        myName.setText(contacts.getContactName());
//                        Glide.with(getActivity())
//                                .load(contacts.getPerson_logo())
//                                .crossFade()
//                                .diskCacheStrategy(DiskCacheStrategy.ALL)
//                                .transform(new GlideCircleTransform_ct(getActivity()))
//                                .centerCrop()
//                                .into(myHeadImageView);
//
//                        LogUtils.e(contacts.toString());
//                    } catch (Exception e1) {
//                        e1.printStackTrace();
//                    }
                }

                @Override
                public void error(String arg0, String arg1) {
                    // 设置登录按钮可用性(登录请求后台有反应后可用)
                    LogUtils.e(arg0+arg1+"55");
                    if (arg0 != null && !arg0.equals("0")){
                        Toast.makeText(getActivity(), arg0 + arg1,
                                Toast.LENGTH_LONG).show();
                    }

                }
            }, json);

        } catch (Exception e) {
            // 设置登录按钮可用性(登录请求后台有反应后可用)
            Log.e("mmmm", e + "");
            e.printStackTrace();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        initTitleBar();
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        ChangeHeadImgObserverUtilTD.getInstance().unRegisterChangeHeadImgObserver(this);
    }

    @OnClick({R.id.my_head_imageView, R.id.my_click_to_my_detail, R.id.my_introduce, R.id.my_click_update, R.id.my_feedback, R.id.my_logout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.my_head_imageView:
                break;
            case R.id.my_click_to_my_detail:
//                if (contacts != null) {
//                    Intent intent = new Intent(getActivity(), ContactsDetailActivity_ct.class);
//                    intent.putExtra("name", contacts.getContactName());
//                    intent.putExtra("cuserId", "isMyself");
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("contact", contacts);
//                    intent.putExtras(bundle);
//                    getActivity().startActivity(intent);
//                }
                break;
            case R.id.my_introduce:
                getActivity().startActivity(new Intent(getActivity(), IntroduceActivity.class));
                break;
            case R.id.my_click_update:
                checkVersion();
                break;
            case R.id.my_feedback:
                break;
            case R.id.my_logout:
                // 先退出 emm,再跳转
                outloginEmm(handler);
                break;
        }
    }

    /****************** emm outlogin start ******************************/

    android.os.Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);


            switch (msg.what) {


                case 4445:  // emm 退出成功
                    StyledDialog.dismissLoading();
                    writeLocationFile("isLoginEmm","false");
                    mActivity.showMessage("退出成功");
                    getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
                    getActivity().finish();

                    break;

                case 4444: // emm 退出失败
                    StyledDialog.dismissLoading();
                    mActivity.showMessage(msg.obj);

                    break;


                case 90000:

                    // 校验
                    checkJudeyApkVersion(msg.obj+"");

                    break;

                default:

                    break;


            }

        }
    };


    // emm 登录注册
    private EnterpriseMobileManager mobileManager = null;
    private String ad_username;

    /**
     * 退出emm
     */
    public void outloginEmm(final Handler handler) {
        loadingDialog = StyledDialog.buildLoading("退出中！").show();
        try {

            // 用户信息
            UserInfoLRY user = mActivity.readLocationObject(Constant.userInfoLry, UserInfoLRY.class);

            if (user == null) {
                StyledDialog.dismissLoading();
                return;
            }

            ad_username = user.getUser_id();

            // emm 退出需要的账号,也就是登陆时候的账号
            ad_username = Constant.emmUserName;


            if (TextUtils.isEmpty(ad_username)) {
                StyledDialog.dismissLoading();
                return;
            }
            Map map = BaseApp_lib.getMap_app();
            String IP_emm = map.get("emm_ip") + "";
            String PORT_emm = map.get("emm_port") + "";

            mobileManager = new EnterpriseMobileManager(
                    getActivity(), IP_emm, PORT_emm, "http");


            SharedPreferences shared = getActivity().getSharedPreferences("UAPHomeConfigure", 0);
            shared.edit().putString("emmhost",IP_emm).commit();
            shared.edit().putString("emmport",PORT_emm).commit();

            //mActivity.showMessage("正在退出...");
            StyledDialog.updateLoadingMsg("努力退出中！");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        mobileManager.cancelUser(ad_username, new com.yonyou.uap.emm.http.HttpCallback() {
                            @Override
                            public void execute(String s) {
                                //LogUtils.e("emm outlogin result: " + s);
                                try {
                                    JSONObject jsonObject = new JSONObject(s);
                                    jsonObject = new JSONObject(jsonObject.optString("data"));
                                    jsonObject = new JSONObject(jsonObject.optString("resultctx"));
                                    String flag = jsonObject.optString("flag");
                                    String desc = jsonObject.optString("desc");
                                    if (TextUtils.isEmpty(flag)) {
                                        LogUtils.e("emm outlogin error");
                                        StyledDialog.dismissLoading();
                                    } else if (!TextUtils.isEmpty(desc) && desc.equals("成功")) {
                                        LogUtils.e("emm outlogin success");
                                        if (handler != null) {

                                            Message message = handler.obtainMessage();
                                            message.what = 4445;
                                            message.obj = "成功";
                                            handler.sendMessage(message);

                                        }

                                    } else {

                                    }
                                } catch (Exception e) {
                                    LogUtils.e("emm outlogin error");

                                    Message message = handler.obtainMessage();
                                    message.what = 4444;
                                    message.obj = e + "";
                                    handler.sendMessage(message);

                                }
                            }
                        });
                    } catch (Exception e) {
                        LogUtils.e(e);


                        Message message = handler.obtainMessage();
                        message.what = 4444;
                        message.obj = e + "";
                        handler.sendMessage(message);


                    }
                }
            }).start();

        } catch (Exception e) {
            StyledDialog.dismissLoading();
            LogUtils.e(e);

        }

    }


    /****************** emm outlogin end ******************************/



    /*********************自动更新**********************/
    /**
     * 功能: 检查版本更新
     * <p/>
     * 日 期: 2016/7/14
     */
    private void checkVersion() {

        if (!CommonUtil.isNetworkConnected(getContext())) {
            Toast.makeText(mActivity, "当前网络不可用，请检查！", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    Object result = HttpUtil.sendPost("https://appstore.yonyou.com/sites/update.php",
                            "type=apk&&name=" + getResources().getString(R.string.description));

                    Message message = Message.obtain();
                    message.what = 90000;
                    message.obj = result;

                    handler.sendMessage(message);
                }
            }).start();
        } catch (Exception e) {
            LogUtils.e("eeee: " + e);
        }
    }

    private void checkJudeyApkVersion(String info){

        try {
            LogUtils.e(info+"");
            JSONObject json = new JSONObject(info);
            int code = json.optInt("code",1);
            String message = json.optString("msg","错误");
            String versionCode = json.optString("versionCode","1.0");
            String update_url = json.optString("update_url","www.baidu.com");
            String update_msg = json.optString("update_msg","更新出错啦!");
            //username.setText(msg.obj+"");
            if(message.equals("检测更新成功")) {
                //保存下载地址和版本
                updateVersionInfo(update_url, versionCode);
                //检查版本
                if (checkupdateVersion()) {
                    new android.support.v7.app.AlertDialog.Builder(getContext())
                            .setTitle(update_msg)
                            .setMessage("检测到有新的版本,是否更新到" + versionCode + "版本")
                            .setNegativeButton(
                                    "更新",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {

                                            String update_url = readLocationValue("update_url");

                                            LogUtils.e("从本地读取update_url = " + update_url);
                                            if (!TextUtils.isEmpty(update_url)) {
                                                updateAppVersion(update_url);
                                            } else {
                                                mActivity.showToast("更新路径URL有误!");
                                            }
                                        }

                                    })
                            .setPositiveButton(
                                    "取消",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(
                                                DialogInterface dialog,
                                                int which) {
                                            dialog.dismiss();
                                                    /*Message message = Message.obtain();
                                                    message.what = 0; // 登录成功
                                                    // 不需要更新
                                                    handler.sendMessage(message);*/

                                        }
                                    }).setCancelable(false).show();
                }
            }else{
                mActivity.showToast("检测更新失败");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * 更新升级版本
     * update_url apk现在地址
     * versioncode 新的apk对应的版本号
     */
    private void updateVersionInfo(String update_url,String versioncode){

        // 记录下,后台的版本信息
        writeLocationFile("app_version",versioncode+"");
        writeLocationFile("update_url",update_url);

    }


    /**
     * 检查更新
     */
    private boolean checkupdateVersion() {

        String app_version = readLocationValue("app_version");
        if (!TextUtils.isEmpty(app_version)) {
            if (!TextUtils.isEmpty(getVersionName())){
                float oldversion = Float.valueOf(getVersionName());
                float newversion = Float.valueOf(app_version);
                // 判断是否需要更新
                if (newversion > oldversion) {
                    return true;
                }else {
                    mActivity.showToast("暂无新版本！");
                }
            }else{
                return false;
            }

        }
        return false;
    }

    /**
     * @return
     *
     * 得到包里的版本名字
     *
     */
    private String getVersionName() {
        try {
            PackageManager packageManager = getActivity().getPackageManager();
            PackageInfo packInfo = packageManager.getPackageInfo(getActivity().getPackageName(), 0);
            return packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
        }
        return "";
    }


    /**
     * 更新app,转到url
     * @param url
     */
    private void  updateAppVersion(String url){
        // 不为空,到升级网址
        if (!TextUtils.isEmpty(url)){
            Uri uri = Uri.parse(url);
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(it);
        }
    }


/*********************自动更新结束**********************/
}
